package com.ikas.ai.server.module.assessment.controller;

import cn.hutool.core.lang.Assert;
import com.ikas.ai.enums.DataTypeEnum;
import com.ikas.ai.handle.JsonResult;
import com.ikas.ai.model.PageQuery;
import com.ikas.ai.server.module.assessment.model.dto.*;
import com.ikas.ai.server.module.assessment.service.AssessModelService;
import com.ikas.ai.server.module.cockpit.model.po.SimplifyRealDataHis;
import com.ikas.ai.server.module.data.model.doris.DorisYxData;
import com.ikas.ai.server.module.data.model.dto.DataTdQueryDto;
import com.ikas.ai.server.module.data.service.DataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工况模型评价管理
 *
 * @author wuyf
 * @menu 工况模型评价管理
 * @since 2023-10-26
 */
@Slf4j
@RestController
@RequestMapping("/assessModel")
public class AssessModelController {

    @Resource
    private AssessModelService assessModelService;

    @Resource
    private DataService dataService;

    /**
     * 分页查询
     *
     * @param queryDto 入参对象
     * @param page     分页信息
     * @return json
     */
    @GetMapping("/page")
    public JsonResult pageAm(AmQueryDto queryDto, PageQuery page) {
        if (StringUtils.isNotBlank(queryDto.getMeteName())) {
            int commaIndex = queryDto.getMeteName().indexOf(',');
            if (commaIndex != -1) {
                queryDto.setMeteName(queryDto.getMeteName().substring(0, commaIndex));
            }
        }
        return JsonResult.ok(assessModelService.pageAm(queryDto, page));
    }

    /**
     * 列表查询
     *
     * @param queryDto 入参对象
     * @return json
     */
    @GetMapping("/list")
    public JsonResult listAm(AmQueryDto queryDto) {
        return JsonResult.ok(assessModelService.listAm(queryDto));
    }

    /**
     * 新增评价模型
     *
     * @param amAddDto 入参对象
     * @return json
     */
    @PostMapping("/add")
    public JsonResult addAm(@RequestBody @Validated AmAddDto amAddDto) {
        assessModelService.addAm(amAddDto);
        return JsonResult.ok();

    }

    /**
     * 修改评价模型
     *
     * @param amUpdateDto 入参对象
     * @return json
     */
    @PostMapping("/update")
    public JsonResult updateAm(@RequestBody @Validated AmUpdateDto amUpdateDto) {
        assessModelService.updateAm(amUpdateDto);
        return JsonResult.ok();
    }

    /**
     * 明细查询
     *
     * @param id 主键id
     * @return json
     */
    @GetMapping("/detail")
    public JsonResult detailAm(@RequestParam Long id) {
        return JsonResult.ok(assessModelService.detailAm(id));
    }

    /**
     * 无效/生效设置
     *
     * @param id 主键id
     * @return json
     */
    @PostMapping("/enable/{id}")
    public JsonResult enableAm(@PathVariable Long id) {
        assessModelService.enableAm(id);
        return JsonResult.ok();
    }

    /**
     * 单个删除
     *
     * @param id 主键id
     * @return json
     */
    @PostMapping("/del/{id}")
    public JsonResult delAm(@PathVariable Long id) {
        assessModelService.delAm(id);
        return JsonResult.ok();
    }

    /**
     * 批量删除
     *
     * @param ids list of id
     * @return json
     */
    @PostMapping("/delBatch")
    public JsonResult delBatchAm(@RequestBody List<Long> ids) {
        assessModelService.delBatchAm(ids);
        return JsonResult.ok();
    }

    /**
     * 从tdEngine根据条件获取数据
     *
     * @param queryDto 入参对象
     * @return page dataHis of json
     */
    @GetMapping("/getMetesOfRp")
    public JsonResult getMetesOfRp(DataTdQueryDto queryDto) {
        return JsonResult.ok(dataService.getDataMetesFromTd(queryDto));
    }

    /**
     * 获取t_data_his表字段类型信息
     *
     * @return map of json
     */
    @PostMapping("/getFieldTypeInfoOfDataHis")
    public JsonResult getFieldTypeInfoOfDataHis(@RequestBody List<String> meteCodes) {
        Assert.isTrue(!CollectionUtils.isEmpty(meteCodes), "meteCodes不能为空");
        Map<String, Object> map = new HashMap<>(meteCodes.size());
        for (String meteCode : meteCodes) {
            //根据meteCode获取最近一条数据
            DorisYxData latestData = dataService.getLatestOneDataMete(null, meteCode, null);
            String valueType = getMeteCodeValueType(meteCode, latestData);
            map.put(meteCode, valueType);
            map.put(meteCode + "_time", DataTypeEnum.BIGINT.getCode());
        }
        return JsonResult.ok(map);
    }

    private String getMeteCodeValueType(String meteCode, DorisYxData latestData) {
        if (latestData != null && StringUtils.isNotBlank(latestData.getValue())) {
            return DataTypeEnum.parseTypeCode(latestData.getValue());
        } else {
            log.warn("没有找到测点{}数据", meteCode);
            return DataTypeEnum.DOUBLE.getCode();
        }
    }

    /**
     * 获取doris获取测点最近条数据的字段类型信息
     *
     * @return map of json
     */
    @GetMapping("/getFieldTypeInfoOfLastData")
    public JsonResult getFieldTypeInfoOfLastData(@RequestParam String machineNo,
                                                 @RequestParam String meteCode,
                                                 @RequestParam(required = false) Long meteId) {
        return JsonResult.ok(
                dataService.getFieldTypeInfoOfLastData(machineNo, meteCode, meteId)
        );
    }


    /**
     * 执行触发模型
     *
     * @param triggerDto 入参对象
     * @return page dataHis of json
     */
    @PostMapping("/triggerModel")
    public JsonResult triggerModel(@RequestBody @Validated AmTriggerDto triggerDto) {
        return JsonResult.ok(assessModelService.triggerModel(triggerDto));
    }


    /**
     * 计算执行项和响应项测点平均时间差
     *
     * @param calDto 文件
     * @return json of double
     */
    @GetMapping("/getAvgTimeByMeteCodes")
    public JsonResult getAvgTimeByMeteCodes(@Validated MeteDataHisCalDto calDto) {
        DataTdQueryDto tdQueryDto = new DataTdQueryDto();
        tdQueryDto.setValidMeteValue(calDto.getValidMeteValueOfExec());
        DataTdQueryDto.LatestNumType latestNumType = new DataTdQueryDto.LatestNumType();
        //如果要去掉最近一条数据，就多查询一条
        if (calDto.getDelTheLastOneData()) {
            calDto.setNumPieces(calDto.getNumPieces() + 1);
        }
        latestNumType.setNum(calDto.getNumPieces());
        tdQueryDto.setLatestNumType(latestNumType);
        //获取执行项的数据
        List<SimplifyRealDataHis> execList = dataService.getRealDataHisFromSonTable(tdQueryDto,
                calDto.getMeteIdOfExec(), calDto.getMeteTypeOfExec());

        //获取响应项的数据 默认多10条数据样本
        tdQueryDto.setLatestNumType(latestNumType);
        tdQueryDto.setValidMeteValue(calDto.getValidMeteValueOfResp());
        List<SimplifyRealDataHis> respList = dataService.getRealDataHisFromSonTable(tdQueryDto,
                calDto.getMeteIdOfResp(), calDto.getMeteTypeOfResp());

        return JsonResult.ok(assessModelService.getAvgTimeByMeteCodes(calDto, execList, respList));
    }

    /**
     * 导入时间数据文件计算平均时差
     *
     * @param file 文件
     * @return
     */
    @PostMapping("/importTimeFileToCalAvgTime")
    public JsonResult importTimeFileToCalAvgTime(@RequestParam MultipartFile file) {
        return JsonResult.ok(assessModelService.importTimeFileToCalAvgTime(file));
    }

}
